import React, { Component } from "react";
import { Input, Form, message } from "antd";
import { currencyPrecisionCal, messages } from "share/common";
import ResizeTable from "components/resize-table/resize-table";
import "styles/expense-report/components/invoice-check-result.scss";
import WrapFormItem from "components/wrap-form-item";

const { TextArea } = Input;
const FormItem = Form.Item;

@Form.create()
class InvoiceCheckResult extends Component {
  state = {
    columns: [],
    reasonRecords: [],
  };

  originColumns = [
    {
      title: messages("common.sequence") /*序号*/,
      dataIndex: "index",
      width: 72,
      render: (value, record, index) => index + 1,
    },
    {
      title: messages("expense-1.key762") /*费用信息*/,
      dataIndex: "expTypeName",
      render: (value, record) => (
        <div>
          {value}
          <br />
          {`${record.invoiceCurrencyCode} ${this.filterMoney(
            record.invoiceAmount,
            currencyPrecisionCal(record.invoiceCurrencyCode),
            true
          )}`}
          <br />
          {record.invoiceCreatedDate}
        </div>
      ),
    },
    {
      title: messages("expense-1.key825") /*校验信息*/,
      dataIndex: "standardExceededLabelToast",
      render: (value) => (
        <div
          style={{ whiteSpace: "normal" }}
          dangerouslySetInnerHTML={{
            __html: value ? value.replace(/&#13;/g, "<br />").replace(/\n/g, "<br />") : "-",
          }}
        />
      ),
    },
  ];

  componentDidMount() {
    this.setColumns();
    this.setReasons();
  }

  setColumns = () => {
    const { isWeakCheck, operation } = this.props;
    const operateColumn = {
      title: <div className="invoice-check-result-reason-title">{messages("expense-1.key796") /*超标原因*/}</div>,
      dataIndex: "standardExceededReason",
      render: (value, record) =>
        operation === "1001" ? this.renderTextArea(record) : <div style={{ whiteSpace: "normal" }}>{value}</div>,
    };
    this.setState({
      columns: isWeakCheck ? this.originColumns.concat(operateColumn) : this.originColumns,
    });
  };

  setReasons = () => {
    const { invoiceList, getReasons } = this.props;
    const reasonRecords = [];
    invoiceList.forEach((item) => reasonRecords.push({ invoiceId: item.invoiceId }));
    this.setState({ reasonRecords });
    getReasons(reasonRecords);
  };

  getCurrentRecordLength = (invoiceId) => {
    const { reasonRecords } = this.state;
    const currentRecord = reasonRecords.find((item) => item.invoiceId === invoiceId) || {};
    return this.safeGet(currentRecord, "record.length") || 0;
  };

  renderTextArea = (record) => {
    const { operation, getReasons } = this.props;
    const { getFieldDecorator } = this.props.form;
    return (
      <FormItem help="">
        {getFieldDecorator(record.invoiceId, {
          rules: [
            {
              validator: (item, value, callback) => {
                if (value && value.value) {
                  callback();
                }
                callback(messages("common.please.input") /*请输入*/);
              },
            },
          ],
        })(
          <WrapFormItem>
            {(valueChange) => (
              <div className="text-area-container">
                <TextArea
                  placeholder={
                    operation === "1001"
                      ? messages("expense-1.key824") /*请输入超标原因*/
                      : messages("expense-1.key823") /*请输入审批意见*/
                  }
                  rows={operation === "1001" ? 3 : 2}
                  maxLength={500}
                  style={{ resize: "none" }}
                  onChange={(e) => {
                    valueChange({ value: e.target.value });
                    const { reasonRecords } = this.state;
                    reasonRecords.map((item) => item.invoiceId === record.invoiceId && (item.record = e.target.value));
                    this.setState({ reasonRecords });
                    getReasons(reasonRecords);
                  }}
                />
                <div className="text-area-container-count">{this.getCurrentRecordLength(record.invoiceId)}/500</div>
              </div>
            )}
          </WrapFormItem>
        )}
      </FormItem>
    );
  };

  render() {
    const { invoiceList, operation } = this.props;
    const { columns } = this.state;
    return columns.length ? (
      <ResizeTable
        rowKey="invoiceId"
        className="invoice-check-result"
        rowClassName="invoice-check-result-row"
        columns={columns}
        dataSource={invoiceList}
        pagination={false}
        expandIconAsCell={false}
        expandedRowRender={operation === "1001" ? null : this.renderTextArea}
        expandedRowKeys={operation === "1001" ? [] : invoiceList.map((item) => item.invoiceId)}
      />
    ) : null;
  }
}

InvoiceCheckResult.propTypes = {
  invoiceList: React.PropTypes.array,
  isWeakCheck: React.PropTypes.bool, // 提交校验是否为弱管控
  operation: React.PropTypes.string, // 1001:提交审批    2001:审批通过
  getReasons: React.PropTypes.func,
};

InvoiceCheckResult.defaultProps = {
  invoiceList: [],
  isWeakCheck: true,
  operation: "",
  getReasons: () => {},
};

export default InvoiceCheckResult;
